package xyy.d3erpapi.service.impl;


import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


import com.google.common.io.LittleEndianDataInputStream;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import xyy.d3erpapi.enums.TaskEnum;
import xyy.d3erpapi.pojo.d3po.OrderDTO;
import xyy.d3erpapi.pojo.d3po.QueryOrderRequestDTO;
import xyy.d3erpapi.pojo.d3po.ResponseSuccessDTO;
import xyy.d3erpapi.pojo.poppo.*;
import xyy.d3erpapi.service.D3Service;
import xyy.d3erpapi.service.PopApiService;
import xyy.d3erpapi.service.PopService;
import xyy.d3erpapi.utils.*;
import xyy.d3erpapi.utils.http.RedirectUtil;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class PopServiceImpl implements PopService {


     @Value("${pop.orgId}")
    private String orgId;

    @Value("${pop.appId}")
    private String appId;

     @Value("${pop.appSecret}")

    private String appSecret ;
     @Value("${d3.appkey}")
     private String d3appKey;

    @Value("${d3.baseurl}")
    private  String baseUrl;

    @Value("${d3.posCode}")
    private  String posCode;

    @Autowired
    private D3Service d3Service;

    @Autowired
    private PopApiService popApiService;







    //
    @Override
    public List<String> queryData(Integer taskId) {

        Map<String, Object> objectMap = buildPopTaskQueryParam(taskId, null);
        String body = RedirectUtil.doGetParam("https://h-api.ybm100.com/api/hackTask/queryTaskCondition", objectMap);
        ApiRPCResult apiRpcResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRpcResult.getData() == null) {
            log.warn("#平台暂时无可用数据 apiRPCResult：{}", JSON.toJSONString(apiRpcResult));
            return new ArrayList<>();
        }
        ResultDto resultData = JSON.parseObject(JSON.toJSONString(apiRpcResult.getData()), ResultDto.class);
        String dataJson = resultData.getDataJson();
        QueryTaskData queryTaskData = JSON.parseObject(dataJson, QueryTaskData.class);
        return queryTaskData.getListQueryParam();
    }


    // 同步库存
    @Override
    public void syncProductStockToPop(List<PopErpSkuStockV2Dto> popErpSkuStockV2Dtos) {
        // 查询 ERP 代码
        List<String> erpCodes = queryData(TaskEnum.PRODUCT_STOCK.getTaskId());

        // 检查 ERP 代码列表是否为空
        if (erpCodes.isEmpty()) {
            log.info("当前没有需要同步库存商品!!!!");
            return;
        }

        // 创建一个新列表，用于存储匹配的 SKU 数据
        List<PopErpSkuStockV2Dto> matchedSkuStockDtos = new ArrayList<>();

        // 遍历 popErpSkuStockV2Dtos，查找匹配的 erpCode
        for (PopErpSkuStockV2Dto skuStockDto : popErpSkuStockV2Dtos) {
            // 检查 erpCode 是否在 erpCodes 列表中
            if (erpCodes.contains(skuStockDto.getErpCode())) {
                matchedSkuStockDtos.add(skuStockDto); // 添加到新列表中
            }
        }

        // 如果没有匹配的 SKU 数据，日志并直接返回
        if (matchedSkuStockDtos.isEmpty()) {
            log.info("没有匹配的商品 数据，无法进行同步!");
            return;
        }


        try {
            // 调用外部服务进行数据推送
            popApiService.pushDataInfo(matchedSkuStockDtos,TaskEnum.PRODUCT_STOCK.getTaskId());
        } catch (Exception e) {
            log.error("同步库存时发生异常", e);
            throw new RuntimeException(e); // 抛出异常以进行上层处理
        }

        log.info("库存同步成功，匹配的 SKU 数据: {}", matchedSkuStockDtos);
    }





    /**
     * 心跳检测
     */
    @Override
    public void syncHeartBeatMonitor() {

        Map<String, Object> objectMap = buildPopTaskQueryParam(00000, null);
        Map<String, String> mapNew = new HashMap<>();
        for (Map.Entry<String, Object> map : objectMap.entrySet()) {
            mapNew.put(map.getKey(), map.getValue().toString());
        }
        log.info("集合 : {}", JSON.toJSONString(objectMap));
        String body = RedirectUtil.doPostByFrom("https://h-api.ybm100.com/api/hackTask/pushClientInfo", mapNew);
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#心跳失败  apiRPCResult: {}", JSON.toJSONString(apiRPCResult));
            return;
        }
        log.info("心跳成功!!!!!");

    }

    //订单推送
    @Override
    public void syncOrderToMerchant() {
        List<SellerOrderInfoDto> sellerOrderInfoDtos = popApiService.pullDataInfo(TaskEnum.ORDER_TOTAL.getTaskId(), SellerOrderInfoDto.class);

        for (SellerOrderInfoDto sellerOrderInfoDto : sellerOrderInfoDtos) {
            OrderDTO orderDTO = convertToOrderDTO(sellerOrderInfoDto);
            if (Objects.isNull(orderDTO)){
            log.warn( "当前订单导入异常请检查!!!:{}", sellerOrderInfoDto.getOrderNo());
                continue;

            }
            // 拼装需要加密的公共参数
            Map<String, String> publicParams = new HashMap<>();
            publicParams.put("appKey", d3appKey);
            publicParams.put("method", "ds.omni.mall.third.order.save");
            publicParams.put("timestamp", String.valueOf(System.currentTimeMillis())); // 生成当前时间戳


            // 使用通用工具类将 orderDTO 转换为 JSON 字符串
            String jsonBusinessParams = JsonUtils.toJson(orderDTO);//orderDTO
            // 生成签名
            String sign = d3Service.validateSignatureToUpper(publicParams, jsonBusinessParams);
            // 将签名加入公共参数
            publicParams.put("sign", sign);

            try {

                // 调用服务或 API 将 orderDTO 发送到点三系统，带上 publicParams
                ResponseSuccessDTO responseSuccessDTO = sendOrder(publicParams, jsonBusinessParams);//
                // 判断 responseSuccessDTO 是否有数据， code 是否为 200
                if (responseSuccessDTO != null && responseSuccessDTO.getResponse().getCode() == 200) {
                    // 调用 public void extracted(@NotNull SellerOrderInfoDto sellerOrderInfoDto) 回调函数
                    extracted(sellerOrderInfoDto);
                    log.info("订单回调成功: Data: {}", sellerOrderInfoDto.getOrderNo());
                } else {
                    // 处理未成功的响应情况
                    log.info("###订单信息回调失败 Data: {}", sellerOrderInfoDto.getOrderNo());
                }
            } catch (Exception e) {
                log.error("发送订单失败，订单号: {}, 错误信息: {}", sellerOrderInfoDto.getOrderNo(), e.getMessage());
            }


      /*  //shopAmount 店铺优惠金额  skuPayPrice 实付单价  skuPrice 原价
        String orderInfoTest ="{\"areaName\":\"苍南县\",\"cityName\":\"温州市\",\"discountAmount\":381.00,\"firstOrder\":1,\"freight\":0.00," +
                "\"merchantId\":55121,\"merchantName\":\"龙港市健宁大药房有限公司\",\"orderCreateTime\":1728803706000,\"orderId\":31751689," +
                "\"orderNo\":\"YBM20241013151505150893\",\"orderState\":1,\"orderType\":1,\"orgId\":\"SH10039022\",\"payAmount\":364.00," +
                "\"payChannel\":2,\"payType\":1,\"pickAddress\":\"浙江省温州市苍南县巴曹社区中魁路153-155号\"," +
                "\"pickName\":\"陈伟智\",\"pickPhone\":\"18867765408\",\"platformAmount\":8.50,\"" +
                "provinceName\":\"浙江省\",\"qualification\":\"\"," +
                "\"sellerOrderDetailLists\":[{\"discountAmount\":381.00,\"erpCode\":\"XO0YY001306\",\"orderDetailId\":226248766," +
                "\"orderId\":31751689,\"orderNo\":\"YBM20241013151505150893\",\"payAmount\":364.00,\"platformAmount\":8.50,\"promoType\":8," +
                "\"purchaseNum\":25,\"purchaseNumDecimal\":25,\"shopAmount\":372.50,\"skuName\":\"傲士 银杏酮酯滴丸(傲士)\",\"skuPayPrice\":14.560000," +
                "\"skuPrice\":29.80,\"skuPurchasePrice\":14.56}]," +
                "\"sellerOrderInvoice\":{\"amountType\":1,\"companyName\":\"龙港市健宁大药房有限公司\"," +
                "\"invoiceAmount\":364.00,\"orderNo\":\"YBM20241013151505150893\",\"reAddress\":\"浙江省温州市苍南县巴曹社区中魁路153-155号\"," +
                "\"registeredAddress\":\"\",\"registeredBank\":\"\",\"registeredBankAccount\":\"\",\"registeredPhone\":\"\"," +
                "\"taxpayerIdentity\":\"91330327MA287HBR3E\",\"type\":1},\"shopAmount\":372.50,\"totalAmount\":745.00}" ;
        SellerOrderInfoDto sellerOrderInfoDto = JsonUtils.convertJsonToObject(orderInfoTest, SellerOrderInfoDto.class);
        OrderDTO orderDTO = convertToOrderDTO(sellerOrderInfoDto);
        // 拼装需要加密的公共参数
            Map<String, String> publicParams = new HashMap<>();
            publicParams.put("appKey", d3appKey);
            publicParams.put("method", "ds.omni.mall.third.order.save");
            publicParams.put("timestamp", String.valueOf(System.currentTimeMillis())); // 生成当前时间戳


            // 使用通用工具类将 orderDTO 转换为 JSON 字符串
            String jsonBusinessParams = JsonUtils.toJson(orderDTO);//orderDTO
            // 生成签名
            String sign = d3Service.validateSignatureToUpper(publicParams, jsonBusinessParams);
            // 将签名加入公共参数
           publicParams.put("sign", sign);

            try {

                // 调用服务或 API 将 orderDTO 发送到点三系统，带上 publicParams
                sendOrder(publicParams,jsonBusinessParams); // 将签名一起发送
            } catch (Exception e) {
                log.error("发送订单失败，订单号: {}, 错误信息: {}", sellerOrderInfoDto.getOrderNo(), e.getMessage());
            }*/
        }}
    //同步退款单
 /*   @Override
    public void syncRefundOrdersToERP() {
        List<SellerRefundOrderDTO> sellerRefundOrderDTOS = popApiService.pullDataInfo(TaskEnum.ORDER_CANCEL.getTaskId(), SellerRefundOrderDTO.class);
        for (SellerRefundOrderDTO sellerRefundOrderDTO : sellerRefundOrderDTOS) {
            OrderDTO orderDTO = convertToOrderDTO(sellerRefundOrderDTO);
            if (Objects.isNull(orderDTO)){
                log.warn( "当前订单导入异常请检查!!!:{}", sellerOrderInfoDto.getOrderNo());
                continue;

            }
            // 拼装需要加密的公共参数
            Map<String, String> publicParams = new HashMap<>();
            publicParams.put("appKey", d3appKey);
            publicParams.put("method", "ds.omni.mall.third.order.save");
            publicParams.put("timestamp", String.valueOf(System.currentTimeMillis())); // 生成当前时间戳


            // 使用通用工具类将 orderDTO 转换为 JSON 字符串
            String jsonBusinessParams = JsonUtils.toJson(orderDTO);//orderDTO
            // 生成签名
            String sign = d3Service.validateSignatureToUpper(publicParams, jsonBusinessParams);
            // 将签名加入公共参数
            publicParams.put("sign", sign);

            try {

                // 调用服务或 API 将 orderDTO 发送到点三系统，带上 publicParams
                ResponseSuccessDTO responseSuccessDTO = sendOrder(publicParams, jsonBusinessParams);//
                // 判断 responseSuccessDTO 是否有数据， code 是否为 200
                if (responseSuccessDTO != null && "200".equals(responseSuccessDTO.getResponse().getCode())) {
                    // 调用 public void extracted(@NotNull SellerOrderInfoDto sellerOrderInfoDto) 回调函数
                    extracted(sellerOrderInfoDto);
                    log.info("订单回调成功: Data: {}", sellerOrderInfoDto.getOrderNo());
                } else {
                    // 处理未成功的响应情况
                    log.info("###订单信息回调失败 Data: {}", sellerOrderInfoDto.getOrderNo());
                }
            } catch (Exception e) {
                log.error("发送订单失败，订单号: {}, 错误信息: {}", sellerOrderInfoDto.getOrderNo(), e.getMessage());
            }


      *//*  //shopAmount 店铺优惠金额  skuPayPrice 实付单价  skuPrice 原价
        String orderInfoTest ="{\"areaName\":\"苍南县\",\"cityName\":\"温州市\",\"discountAmount\":381.00,\"firstOrder\":1,\"freight\":0.00," +
                "\"merchantId\":55121,\"merchantName\":\"龙港市健宁大药房有限公司\",\"orderCreateTime\":1728803706000,\"orderId\":31751689," +
                "\"orderNo\":\"YBM20241013151505150893\",\"orderState\":1,\"orderType\":1,\"orgId\":\"SH10039022\",\"payAmount\":364.00," +
                "\"payChannel\":2,\"payType\":1,\"pickAddress\":\"浙江省温州市苍南县巴曹社区中魁路153-155号\"," +
                "\"pickName\":\"陈伟智\",\"pickPhone\":\"18867765408\",\"platformAmount\":8.50,\"" +
                "provinceName\":\"浙江省\",\"qualification\":\"\"," +
                "\"sellerOrderDetailLists\":[{\"discountAmount\":381.00,\"erpCode\":\"XO0YY001306\",\"orderDetailId\":226248766," +
                "\"orderId\":31751689,\"orderNo\":\"YBM20241013151505150893\",\"payAmount\":364.00,\"platformAmount\":8.50,\"promoType\":8," +
                "\"purchaseNum\":25,\"purchaseNumDecimal\":25,\"shopAmount\":372.50,\"skuName\":\"傲士 银杏酮酯滴丸(傲士)\",\"skuPayPrice\":14.560000," +
                "\"skuPrice\":29.80,\"skuPurchasePrice\":14.56}]," +
                "\"sellerOrderInvoice\":{\"amountType\":1,\"companyName\":\"龙港市健宁大药房有限公司\"," +
                "\"invoiceAmount\":364.00,\"orderNo\":\"YBM20241013151505150893\",\"reAddress\":\"浙江省温州市苍南县巴曹社区中魁路153-155号\"," +
                "\"registeredAddress\":\"\",\"registeredBank\":\"\",\"registeredBankAccount\":\"\",\"registeredPhone\":\"\"," +
                "\"taxpayerIdentity\":\"91330327MA287HBR3E\",\"type\":1},\"shopAmount\":372.50,\"totalAmount\":745.00}" ;
        SellerOrderInfoDto sellerOrderInfoDto = JsonUtils.convertJsonToObject(orderInfoTest, SellerOrderInfoDto.class);
        OrderDTO orderDTO = convertToOrderDTO(sellerOrderInfoDto);
        // 拼装需要加密的公共参数
            Map<String, String> publicParams = new HashMap<>();
            publicParams.put("appKey", d3appKey);
            publicParams.put("method", "ds.omni.mall.third.order.save");
            publicParams.put("timestamp", String.valueOf(System.currentTimeMillis())); // 生成当前时间戳


            // 使用通用工具类将 orderDTO 转换为 JSON 字符串
            String jsonBusinessParams = JsonUtils.toJson(orderDTO);//orderDTO
            // 生成签名
            String sign = d3Service.validateSignatureToUpper(publicParams, jsonBusinessParams);
            // 将签名加入公共参数
           publicParams.put("sign", sign);

            try {

                // 调用服务或 API 将 orderDTO 发送到点三系统，带上 publicParams
                sendOrder(publicParams,jsonBusinessParams); // 将签名一起发送
            } catch (Exception e) {
                log.error("发送订单失败，订单号: {}, 错误信息: {}", sellerOrderInfoDto.getOrderNo(), e.getMessage());
            }*//*
        }
    }*/


    //转换pop订单为点3单据
    private OrderDTO convertToOrderDTO(SellerOrderInfoDto sellerOrderInfoDto){
        OrderDTO orderDTO = new OrderDTO();
        // 填充基本信息
        orderDTO.setRefOid(sellerOrderInfoDto.getOrderNo()); // 订单编号

        orderDTO.setPayNo(""); //支付单号
        orderDTO.setPayment(sellerOrderInfoDto.getPayAmount());//实付金额
        orderDTO.setReceivedPayment("");//已收款金额
        orderDTO.setPostFee(sellerOrderInfoDto.getFreight().toString()); // 快递费用
        orderDTO.setServiceFee("0.00"); // 服务费，假设为 0

        // 收货人信息
        orderDTO.setReceiverName(sellerOrderInfoDto.getPickName()); // 收货人姓名
        orderDTO.setReceiverCountry("中国"); // 假设为中国
        orderDTO.setReceiverState(sellerOrderInfoDto.getProvinceName()); // 假设为省份
        orderDTO.setReceiverCity(sellerOrderInfoDto.getCityName()); // 假设为城市
        orderDTO.setReceiverDistrict(sellerOrderInfoDto.getAreaName()); // 假设为区县
        orderDTO.setReceiverTown("无"); // 假设为街道
        orderDTO.setReceiverAddress(sellerOrderInfoDto.getPickAddress()); // 详细地址
        orderDTO.setReceiverMobile(sellerOrderInfoDto.getPickPhone()); // 收货人手机号
        orderDTO.setReceiverPhone(sellerOrderInfoDto.getPickPhone()); // 收货人电话号码
        orderDTO.setReceiverZip("6542145"); // 假设为邮编

        // 时间信息
        orderDTO.setOrderTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(sellerOrderInfoDto.getOrderCreateTime()) ); // 下单时间
        orderDTO.setModifyTime(""); // 修改时间

        // 买家信息
        orderDTO.setOpenBuyerId(sellerOrderInfoDto.getMerchantId().toString()); // 平台买家id，假设为一个固定值
        orderDTO.setOpenBuyerNick(sellerOrderInfoDto.getMerchantName()); // 买家昵称

        // 支付和发货时间
        orderDTO.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(sellerOrderInfoDto.getOrderCreateTime())); // 支付时间:只有订单创建时间
        orderDTO.setShippingTime(""); // 发货时间

        // 订单状态
        orderDTO.setStatus("NOT_SHIPPED"); // 直接使用状态
        orderDTO.setRefundStatus("NO_REFUND"); // 假设没有退款 status

        // 旗帜状态
        orderDTO.setFlag("NONE"); // 假设为无

        // 备注信息
        orderDTO.setSellerMemo(""); // 假设的卖家备注
        orderDTO.setBuyerMemo(sellerOrderInfoDto.getRemark()); // 买家留言

        // 物流信息
        orderDTO.setLogisticsCompany(""); // 物流公司
        orderDTO.setLogisticsOrderNo(""); // 物流单号

        orderDTO.setPosCode(posCode);
        orderDTO.setBusinessType("GUARANTEE");
        // 创建发票信息
        SellerOrderInvoiceDto sellerOrderInvoice = sellerOrderInfoDto.getSellerOrderInvoice();
        if (sellerOrderInvoice != null) {
            OrderDTO.OrderInvoice orderInvoice = new OrderDTO.OrderInvoice();
            orderInvoice.setBillType(sellerOrderInvoice.getType());
            orderInvoice.setKindType(sellerOrderInvoice.getType());
            orderInvoice.setBillTitle(sellerOrderInvoice.getCompanyName());
            orderInvoice.setTaxpayer(sellerOrderInvoice.getTaxpayerIdentity());
            orderInvoice.setBillContent(""); // 请根据需要设置发票内容
            orderDTO.setOrderInvoice(orderInvoice);
        }

        // 处理订单明细
        List<SellerOrderDetailDto> sellerOrderDetailDtos = sellerOrderInfoDto.getSellerOrderDetailLists();
        if (sellerOrderDetailDtos != null && !sellerOrderDetailDtos.isEmpty()) {
            List<OrderDTO.LineItemDTO> lineItems = new ArrayList<>();
            for (SellerOrderDetailDto sellerOrderDetailDto : sellerOrderDetailDtos) {
                OrderDTO.LineItemDTO lineItem = new OrderDTO.LineItemDTO();
                lineItem.setRefSkuId(sellerOrderDetailDto.getErpCode());//无skuid
                lineItem.setRefSpuId(sellerOrderDetailDto.getErpCode());//无spuid
                lineItem.setSellPrice(sellerOrderDetailDto.getSkuPayPrice().toString());//sku售价   这个为准 商品实付单价
                // do 改成 getPurchaseNumDecimal
                lineItem.setTotalSellPrice(sellerOrderDetailDto.getSkuPayPrice().multiply(sellerOrderDetailDto.getPurchaseNumDecimal()).toString());//售价合计
                lineItem.setTotalPrice(sellerOrderDetailDto.getSkuPrice().multiply(BigDecimal.valueOf(sellerOrderDetailDto.getPurchaseNum())).toString());//原价合计
                lineItem.setTitle(sellerOrderDetailDto.getSkuName());
                lineItem.setPrice(sellerOrderDetailDto.getSkuPrice().toString());
                lineItem.setOuterId(sellerOrderDetailDto.getErpCode());//商家编码
                lineItem.setStandards("");//规格名称
                lineItem.setRefOlId(sellerOrderDetailDto.getOrderDetailId().toString());//源子订单id--订单明细id
                lineItem.setNum(sellerOrderDetailDto.getPurchaseNumDecimal().intValue());
                lineItem.setDiscountFee(sellerOrderDetailDto.getDiscountAmount().toString());
                lineItem.setRefundStatus("NO_REFUND");//货品退款状态
                lineItem.setDiscountFee("");
                lineItem.setStatus("NOT_SHIPPED");//
                lineItem.setBusinessType("GUARANTEE");//不清楚填啥  业务类型
                lineItem.setType("SALE");// 订单类型，固定值：SALE
                lineItem.setPosCode(posCode);//店铺编码
                lineItems.add(lineItem);
            }
            orderDTO.setLines(lineItems);
        }
        return orderDTO;
    }


    //调用点三订单接口
    private ResponseSuccessDTO sendOrder(Map<String, String> publicParams, String jsonBusinessParams) {
        // 构建 URL 查询字符串
        String requestUrl = HttpRequestUtil.buildUrl(baseUrl, publicParams);
        String requestBodyString = jsonBusinessParams;

        // 打印完成的请求参数
        log.info("请求参数: URL: {}, Method: POST, 请求体: {}", requestUrl, requestBodyString);

        // 发送 POST 请求
        HttpResponse response = HttpRequest.post(requestUrl)
                .contentType("application/json;charset=UTF-8")
                .body(jsonBusinessParams)
                .execute();

        // 处理响应
        if (response.getStatus() != 200) {
            log.error("接口请求失败，订单号: {}, 响应码: {}", publicParams != null ? publicParams.get("orderNo") : "unknown", response.getStatus());
            return null; // 或处理错误，抛出异常等
        } else {
            try {

                ResponseSuccessDTO responseSuccessDTO = JSON.parseObject(response.body(), ResponseSuccessDTO.class);
                if (responseSuccessDTO.getResponse()!= null && responseSuccessDTO.getResponse().getCode() == 200) {
                    log.info("订单推送成功: {}", responseSuccessDTO.getResponse().getData());

                    return responseSuccessDTO;
                } else {
                    log.error("接口响应非预期，响应码: {}", responseSuccessDTO.getResponse()!= null? responseSuccessDTO.getResponse().getCode() : "unknown");
                    return null;
                }
            } catch (Exception e) {
                log.error("解析响应失败: {}", e.getMessage());
                return null; // 或其他错误处理
            }
        }
    }


    @Override
    public void syncDeliverInfo(List<SellerOrderDeliverInfoDto> SellerOrderDeliverInfoDtos) {

            //查询是否有需要上报物流的订单号
        List<String> orderNos = queryData(TaskEnum.ORDER_DELIVERY_WMS.getTaskId());
        if (orderNos.isEmpty()) {
            log.info("当前没有需要同步物流的订单!!!!");
            return;
        }
        // 创建一个新列表，用于存储匹配的 SKU 数据
        List<SellerOrderDeliverInfoDto> matchedDeliverInfoDtos = new ArrayList<>();

        // 遍历 popErpSkuStockV2Dtos，查找匹配的 erpCode
        for (SellerOrderDeliverInfoDto deliverInfoDto : SellerOrderDeliverInfoDtos) {
            // 检查 erpCode 是否在 erpCodes 列表中
            if (orderNos.contains(deliverInfoDto.getOrderNo())) {
                matchedDeliverInfoDtos.add(deliverInfoDto); // 添加到新列表中
            }
        }

        // 如果没有匹配的 SKU 数据，日志并直接返回
        if (matchedDeliverInfoDtos.isEmpty()) {
            log.info("没有匹配的物流数据，无法进行同步!");
            return;
        }

        try {
            // 调用外部服务进行数据推送
            popApiService.pushDataInfo(matchedDeliverInfoDtos,TaskEnum.ORDER_DELIVERY_WMS.getTaskId());
        } catch (Exception e) {
            log.error("同步物流时发生异常", e);
            throw new RuntimeException(e); // 抛出异常以进行上层处理
        }

        log.info("物流同步成功，匹配的 SKU 数据: {}", matchedDeliverInfoDtos);

    }


    //订单回调
    public void extracted(@NotNull SellerOrderInfoDto sellerOrderInfoDto) {
        List<SellerOrderCallBackDto> orderCallBackDtos = new ArrayList<>();
        SellerOrderCallBackDto sellerOrderCallBackDto = new SellerOrderCallBackDto();
        sellerOrderCallBackDto.setOrderNo(sellerOrderInfoDto.getOrderNo());
        sellerOrderCallBackDto.setType(1);
        sellerOrderCallBackDto.setOrgId(orgId);
        sellerOrderCallBackDto.setResult(true);
        orderCallBackDtos.add(sellerOrderCallBackDto);
        //订单信息回调
        Map<String, Object> callTask = buildPopTaskQueryParam(10086, orderCallBackDtos);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/callbackForPullTask", JSON.toJSONString(callTask));
    }

    //同步出库信息
    public boolean  syncOrderDeliveryDetails(){
        //调用pop查询接口，是否返回需要上报的订单号
        List<String> orderNos = popApiService.queryData(TaskEnum.ORDER_DELIVERY_DETAILE.getTaskId());
        //无订单号打印日志，结束调用
        if (orderNos.isEmpty()){
            log.info("当前没有需要同步出库信息的商品!!!!");
            //todo  记得改成false
            return false;

        }

        List<SellerOrderDeliverDetailDto> sellerOrderDeliverDetailDtos = d3Service.QueryD3OrderInfo(orderNos);
        if (sellerOrderDeliverDetailDtos.isEmpty() || sellerOrderDeliverDetailDtos.size() <= 0) {
            log.info("未查询到D3出库单信息 Data: {}", JSON.toJSONString(orderNos));
            return false;
        }
        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.ORDER_DELIVERY_DETAILE.getTaskId(), sellerOrderDeliverDetailDtos);
        ApiRPCResult<Boolean> booleanApiRPCResult = popApiService.pushDataInfo(objectMap);
        if (booleanApiRPCResult == null || booleanApiRPCResult.isFail()) {
            log.warn("#出库单数据上报失败  apiRPCResult: {},Data: {}", JSON.toJSONString(booleanApiRPCResult), JSON.toJSONString(sellerOrderDeliverDetailDtos));
            return false;
        }
        log.info("#出库单数据上报成功 Data: {}", JSON.toJSONString(sellerOrderDeliverDetailDtos));

            return  true;
    }


    public <T> List<T> pullDataInfo(Integer taskId, Class<T> tClass) {
        //构建pop订单查询参数
        //构建查询pop参数
        Map<String, Object> objectMap = buildPopTaskQueryParam(taskId, null);
        String body = RedirectUtil.doGetParam("https://h-api.ybm100.com/api/hackTask/pullDataInfo", objectMap);
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#平台数据下推失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(objectMap), JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }
        if (apiRPCResult.getData() == null) {
            log.warn("#平台暂无可拉取数据 apiRPCResult：{}", JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }
        ResultDto resultData = JSON.parseObject(JSON.toJSONString(apiRPCResult.getData()), ResultDto.class);
        String dataJson = resultData.getDataJson();
        List<T> ts = JSON.parseArray(dataJson, tClass);
        return ts;
    }

    private <T> Map<String, Object> buildPopTaskQueryParam(Integer taskId, List<T> list) {


        TaskQueryParam taskQueryParam = new TaskQueryParam();
        taskQueryParam.setOrgId(orgId);
        taskQueryParam.setAppId(appId);
        if (taskId != null && taskId != 00000) {
            taskQueryParam.setTaskId(taskId);
        }
        if (taskId == 00000) {
            String ipAddress = "";
            InetAddress address = IpUtils.getLocalHostLANAddress();
            if (address != null) {
                ipAddress = address.getHostAddress();
            }
            taskQueryParam.setVersion("3.5");
            taskQueryParam.setJsonData(ipAddress);
        }
        if (!CollectionUtils.isEmpty(list)) {
            taskQueryParam.setJsonData(JSON.toJSONString(list));
        }
        Map<String, Object> popParamMap = JSON.parseObject(JSON.toJSONString(taskQueryParam)).getInnerMap();
        taskQueryParam.setSign(MD5Util.encrypt(popParamMap, appSecret));
        Map<String, Object> popParamMapNew = JSON.parseObject(JSON.toJSONString(taskQueryParam)).getInnerMap();
        return popParamMapNew;
    }




}
